package com.github.cosycode.imgtool.tool;

import com.github.cosycode.common.util.common.StrUtils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;

/**
 * <b>Description : </b>
 * <p>
 * <b>created in </b> 2022/8/7
 * </p>
 *
 * @author pengfchen
 * @since 1.0
 **/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class BaseTool {

    public static String findNameFromUrl(String uriString) {
        int e = uriString.lastIndexOf('?');
        if (e < 0) {
            e = uriString.length();
        }
        int s = uriString.lastIndexOf('/', e);
        if (s < 0) {
            throw new IllegalArgumentException("无法正确从 url 中截取出文件名");
        }
        return uriString.substring(s + 1, e);
    }

    public static String findExtFromUrl(String url) {
        String nameFromUrl = BaseTool.findNameFromUrl(url);
        int beginIndex = nameFromUrl.lastIndexOf(".");
        if (beginIndex >= 0) {
            // 获取扩展名
            String ext = nameFromUrl.substring(beginIndex + 1);
            if (ImageCheckTool.MIME_TYPES.contains(ext)) {
                return ext;
            }
        }
        String[] split = ImageCheckTool.MIME_TYPES.split(" ");
        String reg = "\\b((" + StringUtils.join(split, ")|(") + "))\\b";
        final String[] result = new String[1];
        StrUtils.findAllWithBreak(reg, url, s -> {
            result[0] = s;
            return true;
        });
        return result[0];
    }

}
